<script setup>
import {ref,reactive,onMounted, watch, onBeforeMount} from "vue";
import router from "@/router/index.js";
import {getSystemByCode,needCheckCode,getCheckCode,toLogin} from "@/api/basal.js";
import {ResultEnums} from "@/enums/ResultStatusEnums.js";
import {Storage} from "@/utils/Storage.ts";
import Footer from "@/components/debris/AuthFooter.vue";
const system = reactive({systemIcon:'',systemName:''})
const describe = reactive({theme:'后台请求管理系统快捷构建服务',content:'Portal is a free Bootstrap 5 admin dashboard template. You can download and view the template license <a href="https://themes.3rdwavemedia.com/bootstrap-templates/admin-dashboard/portal-free-bootstrap-admin-dashboard-template-for-developers/">here</a>.'})
const login = reactive({loginName:'',loginPassword:'',code:''})
const base64Image = ref("")
const needCode = ref(false)
const errorMessage = reactive({nameError:"",passwordError:"",codeError:"",unKnowError:""})
async function getBase64Image(loginName){
  let image = ""
  if(loginName){
    const result = await getCheckCode(300,30,loginName);
    if(result.code === ResultEnums.SUCCESS){
      image = result.data;
    }
  }
  base64Image.value = image
}
async function checkNeedCode(loginName){
  let need = false;
  if(loginName){
    const result = await needCheckCode(loginName);
    need = result.code === ResultEnums.SUCCESS && result.data
  }
  return need;
}

async function resetCode(loginName){
  needCode.value = await checkNeedCode(loginName)
  if(needCode.value) await getBase64Image(loginName);
}

async function clearError(){
  errorMessage.passwordError = ""
  errorMessage.codeError=""
  errorMessage.unKnowError=""
  errorMessage.nameError=""
}

async function handleLoginSubmit(e) {
  e.preventDefault();
  let loginName = login.loginName;
  if(!loginName){
    await clearError()
    errorMessage.nameError = "请输入账号名称"
    return;
  }
  let password = login.loginPassword;
  if(!password){
    await clearError()
    errorMessage.passwordError = "请输入账号密码"
    return;
  }
  let code = login.code;
  if(!code && needCode.value){
    await clearError()
    errorMessage.codeError = "请输入验证码"
    return;
  }
  const result = await toLogin(loginName,password,code);
  if(result.code === ResultEnums.SUCCESS){
    Storage.set(import.meta.env.VITE_STORE_KEY, result.data)
    // router.push({ path: '/home'});
    window.location.reload();
  }else if(result.code === ResultEnums.NoLoginName){
    await clearError()
    errorMessage.nameError = result.message
    await resetCode(loginName)
  }else if(result.code === ResultEnums.NoCode){
    await clearError()
    errorMessage.codeError = result.message
    await resetCode(loginName)
  }else {
    await clearError()
    errorMessage.unKnowError = result.message
    await resetCode(loginName)
  }
}

onBeforeMount(() => {
  const token = Storage.get(import.meta.env.VITE_STORE_KEY)
  if(token){
    router.push({ path: '/home'});
  }
})

onMounted(() => {
  getSystemByCode(import.meta.env.VITE_SYSTEM_CODE).then(result => {
    if (result.code === ResultEnums.SUCCESS) {
      const data = result.data
      for(const key in data){
        system[key] = data[key]
      }
    }else {
      system.systemIcon = ''
      system.systemName = ''
    }
  })

})
watch(login, (oldValue,newValue) =>  {
  errorMessage.nameError = ""
  errorMessage.unKnowError = ""
  errorMessage.codeError = ""
})

</script>
<template>
  <body class="app app-login p-0">
  <div class="row g-0 app-auth-wrapper">
    <div class="col-12 col-md-7 col-lg-6 auth-main-col text-center p-5">
      <div class="d-flex flex-column align-content-end">
        <div class="app-auth-body mx-auto">
          <div class="app-auth-branding mb-4">
            <a class="app-logo">
              <template v-if="system.systemIcon">
                <img class="logo-icon me-2" :src="system.systemIcon" alt="logo">
              </template>
              <template v-else>
                <img class="logo-icon me-2" src="../../assets/images/app-logo.svg" alt="logo">
              </template>
            </a>
          </div>
          <h2 class="auth-heading text-center mb-5">{{ system.systemName}}</h2>
          <div class="auth-form-container text-start">
            <form class="auth-form login-form">
              <div class="login mb-3">
                <label class="sr-only" for="signin-login">账号</label>
                <input id="signin-login" name="signin-login" type="text" class="form-control signin-login"
                       placeholder="请输入账号名称" required="required" v-model="login.loginName" @blur="resetCode(login.loginName)">
                <Transition>
                  <div class="extra mt-3 row justify-content-between" v-if="errorMessage.nameError">
                    <span class="text-danger">{{ errorMessage.nameError }}</span>
                  </div>
                </Transition>
              </div><!--//form-group-->
              <div class="password mb-3">
                <label class="sr-only" for="signin-password">密码</label>
                <input id="signin-password" name="signin-password" type="password" class="form-control signin-password"
                       placeholder="请输入密码" required="required" v-model="login.loginPassword">
                <Transition>
                  <div class="extra mt-3 row justify-content-between" v-if="errorMessage.passwordError">
                    <span class="text-danger">{{ errorMessage.passwordError }}</span>
                  </div>
                </Transition>
              </div><!--//form-group-->
              <div class="code mb-3" v-if="needCode && login.loginName">
                <label class="sr-only" for="signin-code">验证码</label>
                <input id="signin-code" name="signin-code" type="text" class="form-control signin-code"
                       placeholder="请输入验证码" required="required" v-model="login.code" minlength="4" maxlength="4">
                <Transition>
                  <div class="extra mt-3 row justify-content-between" v-if="errorMessage.codeError">
                    <span class="text-danger">{{ errorMessage.codeError }}</span>
                  </div>
                </Transition>
                <div class="extra mt-3 row justify-content-between">
                  <img :src="`data:image/png;base64,`+base64Image" alt="验证码" @click="getBase64Image(login.loginName)">
                </div>
              </div><!--//form-group-->
              <div class="extra mb-3">
                <Transition>
                  <div class="extra mt-3 row justify-content-between" v-if="errorMessage.unKnowError">
                    <span class="text-danger">{{ errorMessage.unKnowError }}</span>
                  </div>
                </Transition>
<!--                <div class="extra mt-3 row justify-content-between">-->
<!--                  <div class="col-6">-->
<!--                    <div class="form-check">-->
<!--                      <input class="form-check-input" type="checkbox" value="" id="RememberPassword">-->
<!--                      <label class="form-check-label" for="RememberPassword">-->
<!--                        记住我-->
<!--                      </label>-->
<!--                    </div>-->
<!--                  </div>&lt;!&ndash;//col-6&ndash;&gt;-->
<!--                  <div class="col-6">-->
<!--                    <div class="forgot-password text-end">-->
<!--                      <a href="reset-password.html">忘记密码?</a>-->
<!--                    </div>-->
<!--                  </div>&lt;!&ndash;//col-6&ndash;&gt;-->
<!--                </div>&lt;!&ndash;//extra&ndash;&gt;-->
              </div>
              <div class="text-center">
                <button type="submit" class="btn app-btn-primary w-100 theme-btn mx-auto" @click.prevent="handleLoginSubmit($event)">登录</button>
              </div>
            </form>
<!--            <div class="auth-option text-center pt-5">没有账号? 注册 <a class="text-link" href="signup.html" >跳转</a>.</div>-->
          </div><!--//auth-form-container-->

        </div><!--//auth-body-->

        <Footer/><!--//app-auth-footer-->
      </div><!--//flex-column-->
    </div><!--//auth-main-col-->
    <div class="col-12 col-md-5 col-lg-6 h-100 auth-background-col">
      <div class="auth-background-holder">
      </div>
      <div class="auth-background-mask"></div>
      <div class="auth-background-overlay p-3 p-lg-5">
        <div class="d-flex flex-column align-content-end h-100">
          <div class="h-100"></div>
          <div class="overlay-content p-3 p-lg-4 rounded">
            <h5 class="mb-3 overlay-title">{{ describe.theme }}</h5>
            <div v-html="describe.content"></div>
          </div>
        </div>
      </div><!--//auth-background-overlay-->
    </div><!--//auth-background-col-->

  </div><!--//row-->


  </body>
</template>

<style scoped>
.v-enter-active, .v-leave-active {transition: opacity 0.5s ease;}
.v-enter-from, .v-leave-to {opacity: 0;}
</style>